package com.cb.controller.front.order;


import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import net.sf.json.xml.XMLSerializer;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import com.cb.common.constants.PolicyConstants;
import com.cb.common.map.Constants;
import com.cb.common.util.ConfigUtil;
import com.cb.common.util.MathUtil;
import com.cb.domain.model.order.Policy;
  
/** 
 * common xml conver utility 
 *  
 * @author sdm
 * @version Framework 2010.10.26 
 */  
public class XmlConverUtil {  
    /** 
     * map to xml xml <node><key label="key1">value1</key><key 
     * label="key2">value2</key>......</node> 
    *  
    * @param map 
    * @return 
    */ 
	
	public List<Policy> list;
	
   public List<Policy> getList() {
		return list;
	}

	public void setList(List<Policy> list) {
		this.list = list;
	}

public String maptoXml(Map map) {  
       Document document = DocumentHelper.createDocument();  
       Element nodeElement = document.addElement("node");  
       for (Object obj : map.keySet()) {  
           Element keyElement = nodeElement.addElement("key");  
           keyElement.addAttribute("label", String.valueOf(obj));  
           keyElement.setText(String.valueOf(map.get(obj)));  
       }  
       return doc2String(document);  
   }  
 
   /** 
    * list to xml xml <nodes><node><key label="key1">value1</key><key 
    * label="key2">value2</key>......</node><node><key 
    * label="key1">value1</key><key 
    * label="key2">value2</key>......</node></nodes> 
    *  
    * @param list 
    * @return 
    */  
   public String listtoXml(List list) throws Exception {  
       Document document = DocumentHelper.createDocument();  
       Element nodesElement = document.addElement("nodes");  
       int i = 0;  
       for (Object o : list) {  
           Element nodeElement = nodesElement.addElement("node");  
           if (o instanceof Map) {  
        	   //foreach map
               for (Object obj : ((Map) o).keySet()) {/*  
            	   Object object= ((Map) o).get(obj);

            	   //while obj equals ArrayList,that's child
                   if(object instanceof ArrayList){
                	   if(((ArrayList)object).size()>0){
                	   Element childEle=nodeElement.addElement("node");
                	   List childList=(List)object;
                	   //foreach child Map
                	   for (Object childO : childList) { 
                		   if (childO instanceof Map) { 
                			   for (Object childObj : ((Map) childO).keySet()) { 
                				   Element childKeyElement = childEle.addElement("key");  
                				   childKeyElement.addAttribute("label", String.valueOf(childObj));  
                				   childKeyElement.setText(String.valueOf(((Map) childO).get(childObj)));  
                			   }
                		   }
                	   }}
                   }else{
                	   Element keyElement = nodeElement.addElement("key");  
                       keyElement.addAttribute("label", String.valueOf(obj));  
                       keyElement.setText(String.valueOf(((Map) o).get(obj)));  
                   }
               */
            	   
            	   
            	   Object mapValue=((Map)o).get(obj.toString());
            	   if(mapValue instanceof List){
            		   Element keyElement = nodeElement.addElement("Classes");  
            		   for(Object temp:(List)mapValue){
            			   if(temp instanceof Map){
            				   
            				   	  if(((Map) temp).size()==0)continue;
            			          Element classElement = keyElement.addElement("Class");
            			          for(Object key:((Map)temp).keySet()){
            			        	  Element classChildElement=classElement.addElement(String.valueOf(key));
            			        	  classChildElement.setText(String.valueOf(((Map) temp).get(key)));
//            			        	  classElement.addAttribute(,);  
            			          }
  
            			   }
            		   }
            	   }else{
            		   Element otherElement=nodeElement.addElement(obj.toString());
            		   otherElement.setText(mapValue.toString());
            	   }
         
               
               }  
           } else {  
               Element keyElement = nodeElement.addElement("key");  
               keyElement.addAttribute("label", String.valueOf(i));  
               keyElement.setText(String.valueOf(o));  
           }  
           i++;  
       }  
       return doc2String(document);  
   }  
 
   /** 
    * json to xml {"node":{"key":{"@label":"key1","#text":"value1"}}} conver 
    * <o><node class="object"><key class="object" 
    * label="key1">value1</key></node></o> 
    *  
    * @param json 
    * @return 
    */  
   public String jsontoXml(String json) {  
       try {  
           XMLSerializer serializer = new XMLSerializer();  
           JSON jsonObject = JSONSerializer.toJSON(json);  
           return serializer.write(jsonObject);  
       } catch (Exception e) {  
           e.printStackTrace();  
       }  
       return null;  
   }  
 
   /** 
    * xml to map xml <node><key label="key1">value1</key><key 
    * label="key2">value2</key>......</node> 
    *  
     * @param xml 
     * @return 
     */  
    @SuppressWarnings("rawtypes")
	public Object xmltoMap(String xml) {  
        try {  
            Map map = null;  
            Document document = DocumentHelper.parseText(xml);  
            Element nodeElement = document.getRootElement();  
            List node = nodeElement.elements();  
            if(node.size()>0){
            	map=new HashMap();
            }
            for (Iterator it = node.iterator(); it.hasNext();) {
            	
                Element elm = (Element) it.next();
                if(elm.elements().size()>0){
                	 List<Map> list = new ArrayList<Map>(); 
                	 List childNode= elm.elements();
                	for (Iterator childIt =childNode.iterator(); childIt.hasNext();) { 
                		  Element childElm = (Element) childIt.next(); 
                		 String isShare=nodeElement.element("ShareCarrier").getTextTrim();
                		  if(StringUtils.isBlank(isShare)){
	                		  Map  childMap=childXmltoMap(childElm,nodeElement);
	                		  if(childMap!=null&&childMap.size()>0){
	                		  list.add(childMap);
	                		  }
                		  }
                		 childElm=null;
					}
                	//排序
            /*        Collections.sort(list, new Comparator<Map>(){  
                        public int compare(Map o1, Map o2) 
                        {  
                            //取出操作时间  
                            int ret = 0;  
                            ret = (Double.valueOf((String) o1.get("price"))).compareTo(Double.valueOf((String) o2.get("price")));  
                            return  ret;  
                        }  
                          
                    });  */
                	sortListByPriceAsc(list);
                	 map.put(elm.getName(),list );  
                	 childNode = null;  
                }else{
                	map.put(elm.getName(), elm.getText());  
                }
                elm = null;  
            }  
           
            if(map!=null){
            	String tmpStr=(String) map.get("TPM");
	            Long tpm=Long.valueOf(tmpStr);
	            Long fuelSurTax=Long.valueOf(ConfigUtil.getInstance().getXmlValByStr("lower.fuelSurTax", "80"));
	            Long mileage=Long.valueOf(ConfigUtil.getInstance().getXmlValByStr("mileage.standards", "800"));
	            if(tpm>mileage){
	            	fuelSurTax=Long.valueOf(ConfigUtil.getInstance().getXmlValByStr("higher.fuelSurTax", "150"));
	            }
	            map.put("fuelSurTax", fuelSurTax); 
	            
	            
	        	String aircraft=(String) map.get("Aircraft");
	            String compareAircraft=ConfigUtil.getInstance().getXmlValByStr("aircraft", "");
	            if(compareAircraft.indexOf(aircraft)!=-1){
	            	 map.put("AirportTax", "0"); 
	            }
            }
            node = null;  
            nodeElement = null;  
            document = null;  
            return map;  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return null;  
    }  
  
    
    private void sortListByPriceAsc(List<Map> list){
    	for(int i=0;i<list.size();i++){
    		  for(int j=list.size()-1;j>i;--j){
    			  String price1=list.get(j).get("price").toString();
    			  String price2=list.get(j-1).get("price").toString();
    			  if(StringUtils.isNotEmpty(price1)&&StringUtils.isNotEmpty(price2)){
    				  if(Double.valueOf(price1)<Double.valueOf(price2)){
    					  Map temp=list.get(j);
    					  list.set(j, list.get(j-1));
    					  list.set(j-1, temp);
    				  }
    			  }
    		  }
    	}
    }
    
    /** 
     * xml to map xml <node><key label="key1">value1</key><key 
     * label="key2">value2</key>......</node> 
     *  
      * @param xml 
      * @return 
      */  
     @SuppressWarnings("unchecked")
	public  Map childXmltoMap(Element childRoot,Element elm) {  
         try {  
        	  Map map = null;  
             String code=childRoot.attributeValue("Code");
             if(StringUtils.isNotEmpty(code)){
	             map=new HashMap();
	             String ticketPrice=childRoot.attributeValue("Price");
//	             ticketPrice="100";
	             String seat=childRoot.attributeValue("Seat");
	             String carrier=elm.element("Carrier").getTextTrim();
	             //仓位
	 			 map.put("code", code);
	 			 map.put("Ext", "");
	 			 //座位
	     		 map.put("Seat", seat);
	     		 //折扣了多少钱
	     		 map.put("discount", "0");
	     		 //原票价
	     		 map.put("ticketPrice", ticketPrice);
	     		 //折扣后票价
	     		 map.put("price", ticketPrice);
	     		 //政策ID
	     		 map.put("policyId", "");
	     		 //退改签说明
	     		 map.put("backNote", "");
	     		 //舱位说明
	     		 map.put("cabinNote","");
	     		 
	     		Boolean isHaveSeat=false;
	 			if(MathUtil.isNumeric(seat)){
	 				if(Integer.parseInt(seat)>0){
	 					isHaveSeat=true;
	 				}
	 			}else if(seat.equalsIgnoreCase("A")){
	 				isHaveSeat=true;
	 			}
	     		Double policyPrice=0d;
	     		
	     		//四折特殊仓位计算
	         	String discountCarriers=ConfigUtil.getInstance().getXmlValByStr("carrier", "");
	         	String discountCodes=ConfigUtil.getInstance().getXmlValByStr("code", "");
	         	String [] discountCarrierArray=discountCarriers.split(",");
	         	String [] discountCodeArray=discountCodes.split(",");
	         	for (int i = 0; i < discountCodeArray.length; i++) {
					if(discountCarrierArray[i].equalsIgnoreCase(carrier)&&discountCodeArray[i].equalsIgnoreCase(code)&&isHaveSeat){
						 String YClassPrice=elm.element("YClassPrice").getTextTrim();
						 policyPrice=Double.valueOf(YClassPrice)*0.4;
					    long converter=policyPrice.longValue();
						long absPrice= (converter%10 <5)?converter/10*10:converter/10*10+10;
						ticketPrice=String.valueOf(absPrice);
						 map.put("ticketPrice", YClassPrice);
			     		 //折扣后票价
			     		 map.put("price", absPrice);
						 break;
					}
				}
	     		
	             if(null!=list&&list.size()>0&&StringUtils.isNotEmpty(ticketPrice)&&StringUtils.isNotEmpty(code)&&StringUtils.isNotEmpty(carrier)){
	            	 	Double ticketPriceVal=Double.valueOf(ticketPrice);
//	            	 	if(ticketPriceVal>0){
	            	 		for (Policy policy:list) {
	            	 			//判断是否复核舱位和航空公司
	            	 		
	            	 			if(isHaveSeat || policy.getCabin().indexOf(code)!=-1){
	            	 			policyPrice=Double.valueOf(ticketPrice);
				        		if(policy.getCabin().indexOf(code)!=-1&&policy.getFlightCode().equalsIgnoreCase(carrier)){
				        			String xmlFlightNo=elm.element("FlightNo").getTextTrim();
				        			if(StringUtils.isNotEmpty(xmlFlightNo)){
				        				String flightNo=carrier+xmlFlightNo;
				        				//判断航班号是否符合政策条件及今天是否符合政策范围
				        				if(checkCondition(flightNo, policy)&&checkDay(policy.getDaycondition())){
					        				//原价*0.12+-10
				        					if(policy.getPolicyType().equals(PolicyConstants.LOWPRICE)){
				        						if(policy.getDiscountType().equals(PolicyConstants.DISCOUNTYPE_Y_VALUE)){
				        							String yValue=elm.element("YClassPrice").getTextTrim();
				        							ticketPriceVal=policy.getDiscountValue()*(Double.valueOf(yValue));
				        						}else if(policy.getDiscountType().equals(PolicyConstants.DISCOUNTYPE_ZD_VALUE)){
				        							ticketPriceVal=policy.getDiscountValue();
				        						}
				        					}
						        		    policyPrice=ticketPriceVal-ticketPriceVal*policy.getReturnPoint().doubleValue()/100+policy.getReturnPrice().doubleValue();
						        		    policyPrice= Math.ceil(policyPrice);
						        		    map.put("price", policyPrice.toString());
						        			Double discount=ticketPriceVal-policyPrice;
						        			map.put("discount", discount.toString());
						        			map.put("policyId", policy.getPolicyId().toString());
						        			map.put("backNote", policy.getBackNote());
						        			map.put("cabinNote", policy.getCabinNote());
						        			break;
				        				}
				        			}
				        		}
	        				}}
//	            	 	}
			        	
			        }
	             
		         	if(list.size()==0&& isHaveSeat){
	    	 			policyPrice=Double.valueOf(ticketPrice);
	    	 		}   
		         
		         	/*else{
			        	map=new HashMap();
			        }*/
		         	if(/*Double.valueOf(ticketPrice)==0&&*/policyPrice==0||!isHaveSeat){
	    	 			return new HashMap();
	    	 		}
             }
             return map;  
         } catch (Exception e) {  
             e.printStackTrace();  
         }  
         return null;  
     }  
     
     /**
      * 判断航班号是否适用于政策
      * @param targetFlightNo
      * @param conditionType
      * @param conditionFlightNos
      * @return
      */
     private static boolean checkCondition(String targetFlightNo,Policy policy){
    	 boolean res=false;
    	 String conditionType=policy.getFlightNumLimit();
    	 String conditionNos=policy.getFlightCondition();
    	 if(conditionType.equals(PolicyConstants.FLIGHT_CONDITION_ALL)){
    		 res=true;
    	 }else if(conditionType.equals(PolicyConstants.FLIGHT_CONDITION_WITHOUT)){
    		 if(conditionNos.indexOf(targetFlightNo)==-1){
    			 res=true;
    		 }
    	 }else{
    		 if(conditionNos.indexOf(targetFlightNo)!=-1){
    			 res=true;
    		 }
    	 }
    	 return res;
     }
     
     /**
      * 判断今天的星期几是否包含在参数字符串里面
      * @param includes
      * @return
      */
     private static boolean checkDay(String includes){
    	 boolean res=false;
    	 Date nowDay=new Date();
    	 Integer dayIndex=nowDay.getDay();
    	 if(includes.indexOf(dayIndex.toString())!=-1){
    		 res=true;
    	 }
    	 return res;
     }
     
     
    /** 
     * xml to list xml <nodes><node><key label="key1">value1</key><key 
     * label="key2">value2</key>......</node><node><key 
     * label="key1">value1</key><key 
     * label="key2">value2</key>......</node></nodes> 
     *  
     * @param xml 
     * @return 
     */  
     
	@SuppressWarnings({ "rawtypes", "rawtypes" })
	public List xmltoList(String xml) {  
        try {  
            List list = new ArrayList();  
            Document document = DocumentHelper.parseText(xml);  
            Element nodesElement = document.getRootElement();  
            List nodes = nodesElement.elements();  
            for (Iterator its = nodes.iterator(); its.hasNext();) {  
                Element nodeElement = (Element) its.next();  
                Object map = xmltoMap(nodeElement.asXML());  
                if(map!=null){
                list.add(map);  
                }
            }  
            return list;  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return null;  
    }  
  
    /** 
     * xml to json <node><key label="key1">value1</key></node> 转化为 
     * {"key":{"@label":"key1","#text":"value1"}} 
     *  
     * @param xml 
     * @return 
     */  
    public String xmltoJson(String xml) {  
        XMLSerializer xmlSerializer = new XMLSerializer();  
        return xmlSerializer.read(xml).toString();  
    }  
  
    /** 
     *  
     * @param document 
     * @return 
     */  
    public String doc2String(Document document) {  
        String s = "";  
        try {  
            // 使用输出流来进行转化   
            ByteArrayOutputStream out = new ByteArrayOutputStream();  
            // 使用UTF-8编码   
            OutputFormat format = new OutputFormat("   ", true, "UTF-8");  
            XMLWriter writer = new XMLWriter(out, format);  
            writer.write(document);  
            s = out.toString("UTF-8");  
        } catch (Exception ex) {  
            ex.printStackTrace();  
        }  
        return s;  
    }  
    
    /**
     * String转XML DOCUMENT
     * @param xmlContent
     * @return
     */
    public static Document str2Xml(String xmlContent){
    	Document doc=null;
    	try {
			doc=DocumentHelper.parseText(xmlContent);
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return doc;
    }
    
    public static void main(String [] args){
    	String days="13467";
    	boolean res=checkDay(days);
    	System.out.println("123");
    }
}  
